package com.up.upzl.filter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.Map;
import java.util.Objects;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.json.JacksonJsonParser;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Maps;
import com.up.upzl.biz.domain.User;
import com.up.upzl.biz.service.UserService;

import utils.JwtUtil;

public class JWTLoginFilter extends UsernamePasswordAuthenticationFilter {

	private static final Logger log = LoggerFactory.getLogger(JWTLoginFilter.class);
	private AuthenticationManager authenticationManager;
	private UserService userService;

	public JWTLoginFilter(AuthenticationManager authenticationManager, UserService userService) {
		this.authenticationManager = authenticationManager;
		this.userService = userService;
	}

	// 接收并解析用户凭证
	@Override
	public Authentication attemptAuthentication(HttpServletRequest req, HttpServletResponse res)
			throws AuthenticationException {
	
		String account=req.getParameter("account");
		String password=req.getParameter("password");
//		StringBuilder content = new StringBuilder();  
//	    byte[] b = new byte[1024];  
//	    int lens = -1;  
//	    try {
//			while ((lens = req.getInputStream().read(b)) > 0) {  
//			    content.append(new String(b, 0, lens));  
//			}
//			System.out.println(content.toString());
//		} catch (IOException e1) {
//		
//			e1.printStackTrace();
//		}  
		try {
			//User user = new ObjectMapper().readValue(req.getInputStream(), User.class);
            User user=new User();
            user.setAccount(account);
            user.setPassword(password);
			return authenticationManager.authenticate(
					new UsernamePasswordAuthenticationToken(user.getAccount(), user.getPassword(), new ArrayList<>()));
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	// 用户成功登录后，这个方法会被调用，我们在这个方法里生成token
	@Override
	protected void successfulAuthentication(HttpServletRequest req, HttpServletResponse res, FilterChain chain,
			Authentication auth) throws IOException, ServletException {
		log.info("==>用户登录 成功");
		String username = ((org.springframework.security.core.userdetails.User) auth.getPrincipal()).getUsername();
		String header = req.getHeader("Authorization");
		if (header == null || !header.startsWith("Bearer ")) {
			String token = JwtUtil.buildJWT(username, null, null, null, Maps.newHashMap(), null, 60);
			log.info("token:{}", token);
			res.addHeader("Authorization", token);
			User user = userService.findByAccount(username);
			if (Objects.isNull(user.getFirstTime())) {
				user.setFirstTime(new Date());
			}
			user.setLoginCount(user.getLoginCount() + 1);
			userService.editUser(user);
		}
		Map  map=Maps.newHashMap();
		map.put("code", "200");
		map.put("phone", username);
		map.put("pvCount", 0);
		map.put("message", "success");
		String json =new  ObjectMapper().writeValueAsString(map);
		log.info("<<== 登录成功返回json:{}",json);;
		res.getWriter().print(json);

	}
}
